package com.wx.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * <p>Title:      SnowFlakeUtils. </p>
 * <p>Description id生成工具类 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since 2021/2/1 20:06
 */
public class SnowFlakeUtil {

    private long machineId;

    private long dataCenterId;


    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    public static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(1L, 1L);
    }

    private Snowflake snowflake = IdUtil.createSnowflake(machineId, dataCenterId);

    public synchronized long id() {
        return snowflake.nextId();
    }

    public static Long getId() {
        return SnowFlakeUtil.get().id();
    }

    public static String getStringId() {
        return String.valueOf(SnowFlakeUtil.get().id());
    }
}
